// Copyright 2024 Ant Group Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package modules

import (
	"context"
	"fmt"
	"time"

	"github.com/secretflow/kuscia/pkg/diagnose/app/server"
	"github.com/secretflow/kuscia/pkg/diagnose/common"
	"github.com/secretflow/kuscia/pkg/utils/nlog"
	"github.com/secretflow/kuscia/pkg/utils/readyz"
)

type diagnoseModule struct {
	moduleRuntimeBase
	diagnoseServer *server.HTTPServerBean
}

func NewDiagnose(d *ModuleRuntimeConfigs) (Module, error) {
	diagnoseServer := server.NewHTTPServerBean(d.Clients)

	return &diagnoseModule{
		moduleRuntimeBase: moduleRuntimeBase{
			rdz:          readyz.NewHTTPReadyZ(fmt.Sprintf("http://127.0.0.1:%d/%s/%s", diagnoseServer.Config.HTTPPort, common.DiagnoseNetworkGroup, common.DiagnoseHealthyPath), 200, nil),
			readyTimeout: 60 * time.Second,
			name:         "diagnose",
		},
		diagnoseServer: diagnoseServer,
	}, nil
}

func (d *diagnoseModule) Run(ctx context.Context) error {
	err := d.diagnoseServer.Run(ctx)
	if err != nil {
		nlog.Warnf("failed to run diagnose server %s", err.Error())
	}
	return nil
}

func (d *diagnoseModule) WaitReady(ctx context.Context) error {
	return nil
}

func (d *diagnoseModule) Name() string {
	return "diagnose"
}
